<?php

namespace WeForge\Queue;

use HttpClient\Aliyun\MessageNotificationService\Application as Mns;
use HttpClient\RequestException;
use Illuminate\Contracts\Queue\Queue as QueueContract;
use Illuminate\Queue\Queue;

class MnsQueue extends Queue implements QueueContract
{
    /**
     * @var \HttpClient\Aliyun\MessageNotificationService\Application
     */
    protected $mns;

    /**
     * The name of the default queue.
     *
     * @var string
     */
    protected $default;

    /**
     * Create a new MnsQueue instance.
     *
     * @param \HttpClient\Aliyun\MessageNotificationService\Application $mns
     * @param string $default
     */
    public function __construct(Mns $mns, $default)
    {
        $this->mns = $mns;
        $this->default = $default;
    }

    /**
     * Get the size of the queue.
     *
     * @param  string|null  $queue
     * @return int
     */
    public function size($queue = null)
    {
        return (int) $this->mns->queue->get($this->getQueue($queue))['ActiveMessages'];
    }

    /**
     * Push a new job onto the queue.
     *
     * @param  string|object  $job
     * @param  mixed  $data
     * @param  string|null  $queue
     * @return mixed
     */
    public function push($job, $data = '', $queue = null)
    {
        return $this->pushRaw(
            $this->createPayload($job, $this->getQueue($queue), $data),
            $queue
        );
    }

    /**
     * Push a raw payload onto the queue.
     *
     * @param  string  $payload
     * @param  string|null  $queue
     * @param  array  $options
     * @return mixed
     */
    public function pushRaw($payload, $queue = null, array $options = [])
    {
        // dd(base64_encode($payload));
        return $this->mns->queue_message->send(
            $this->getQueue($queue),
            base64_encode($payload)
        )['MessageId'];
    }

    /**
     * Push a new job onto the queue after a delay.
     *
     * @param  \DateTimeInterface|\DateInterval|int  $delay
     * @param  string|object  $job
     * @param  mixed  $data
     * @param  string|null  $queue
     * @return mixed
     */
    public function later($delay, $job, $data = '', $queue = null)
    {
        return $this->mns->queue_message->send(
            $this->getQueue($queue),
            base64_encode($this->createPayload($job, $this->getQueue($queue), $data)),
            $this->secondsUntil($delay)
        )['MessageId'];
    }

    /**
     * Pop the next job off of the queue.
     *
     * @param  string  $queue
     * @return \Illuminate\Contracts\Queue\Job|null
     */
    public function pop($queue = null)
    {
        return $this->receiveQueueMessage($queue = $this->getQueue($queue), function ($job) use ($queue) {
            return new MnsJob(
                $this->container,
                $this->mns,
                $job,
                $this->connectionName,
                $queue
            );
        });
    }

    /**
     * Get the underlying MNS instance.
     *
     * @return \HttpClient\Aliyun\MessageNotificationService\Application
     */
    public function getMns()
    {
        return $this->mns;
    }

    /**
     * @param  string $queue
     * @param  \Closure $callback
     *
     * @return mixed
     */
    protected function receiveQueueMessage($queue, $callback)
    {
        try {
            return $callback(
                $this->mns->queue_message->receive($queue)->toArray()
            );
        } catch (RequestException $e) {
            throw_unless($e->response->getStatusCode() === 404, $e);
        }
    }

    /**
     * @param  string $queue
     * @return string
     */
    protected function getQueue($queue)
    {
        return $queue ?: $this->default;
    }
}
